// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#include "coin2/exchange/btcturk/api_order/native_private_client.h"

#include <memory>
#include <sstream>

#include "coin2/exchange/base/api_util/url_params_builder.h"
#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/btcturk/api_util/rate_tracker.h"
#include "coin2/exchange/btcturk/symbology/product.h"

using coin2::exchange::btcturk::symbology::BtcturkProduct;

#define CHECK_API_LIMIT(action_type, query_type)                                          \
  if (!local_rate_tracker_->HasEnoughRateLimit(ts, action_type, query_type)) {            \
    if (order_logger_cb_) {                                                               \
      rate_tracker_->WriteRateLimitReportMessage(order_logger_cb_);                       \
    }                                                                                     \
    LOG_EVERY_N(WARNING, 50) << "Hit rate limit or api temporary disabled, " << __func__; \
    api_block_info_[__func__]++;                                                          \
    return {};                                                                            \
  }

auto BtcturkNativePrivateClient::GetRestOrderParams(
    const OrderSpec& order_spec,
    int64_t proc_order_id) -> RestParams {
  auto params = RestParams();
  BtcturkProduct product =
      BtcturkProduct::FromStr(order_spec.product, order_spec.order_created_time);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  params.set_pair_symbol(order_spec.product);
  params.set_client_order_id(std::to_string(proc_order_id));
  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_order_type("buy");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_order_type("sell");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }
  auto formatter = product_holder->product_info().order_formatter();
  params.set_quantity(formatter.FormatQty(order_spec.qty));
  if (order_spec.order_type != OrderType::MARKET_ORDER) {
    params.set_price(formatter.FormatPrice(order_spec.price));
  }
  if (order_spec.order_type == OrderType::LIMIT_ORDER) {
    params.set_order_method("limit");
  } else if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_order_method("market");
  } else {
    NOTREACHED() << "Unknown order type: " << static_cast<int>(order_spec.order_type);
  }

  return params;
}

auto BtcturkNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context)
    -> RestParams {
  auto params = RestParams();
  if (order_context.has_exchange_order_id()) {
    params.set_order_id(order_context.exchange_order_id());
  } else {
    CHECK(false) << "[GetRestCancelParams] Order ID is required";
    params.set_client_order_id(std::to_string(order_context.proc_order_id()));
  }

  return params;
}

BtcturkNativePrivateClient::BtcturkNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config_override) {
  mea_ = mea;
  using coin2::exchange::btcturk::api_util::BtcturkRateTracker;
  NativeClientConfig config;
  config.set_rest_host("api.btcturk.com");
  config.set_rest_host_port(443);
  config.MergeFrom(config_override);
  LOG(INFO) << "[BtcturkNativePrivateClient] config: " << config.DebugString();

  auths_.Construct<BtcturkRestAuth, NativeClientConfig>(config);

  rate_tracker_ = std::make_unique<BtcturkRateTracker>(mea_, config);
  local_rate_tracker_ = dynamic_cast<BtcturkRateTracker*>(rate_tracker_.get());
  start_time_ = GetCurrentTimestamp();
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::QueryAccountBalance() {
  auto ts = GetCurrentTimestamp();
  CHECK_API_LIMIT(ActionType::QUERY, QueryType::BALANCE);

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/v1/users/balances", &builder);
  local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::BALANCE);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::REST_ACCOUNT_BALANCE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::QueryOpenOrders(
    const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  CHECK_API_LIMIT(ActionType::QUERY, QueryType::OPEN_ORDER);

  UrlParamsBuilder builder;
  builder.PutGet("pairSymbol", params.pair_symbol());
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/v1/openOrders", &builder);
  local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::OPEN_ORDER);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::QueryHistoryOrders(
    const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  CHECK_API_LIMIT(ActionType::QUERY, QueryType::HIST_ORDER);

  UrlParamsBuilder builder;
  builder.PutGet("pairSymbol", params.pair_symbol());
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/v1/allOrders", &builder);
  local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::HIST_ORDER);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::REST_DONE_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::QueryFills(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  CHECK_API_LIMIT(ActionType::QUERY, QueryType::FILL_ORDER);

  UrlParamsBuilder builder;
  builder.PutGet("symbol", params.symbol());
  builder.PutGet("type", params.type());
  auto* context =
      GetAuth()->CreateRequestByGetWithSignature("/api/v1/users/transactions/trade", &builder);
  local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::FILL_ORDER);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

void BtcturkNativePrivateClient::Prepare() {
  mb_->Subscribe("btcturk/enable_time", [this](const std::string&, void* data) {
    int64_t value = reinterpret_cast<int64_t>(data);
    local_rate_tracker_->UpdateEnableTime(value);
    LOG(WARNING) << "Btcturk native client enable_time: " << value;
  });
}

std::string BtcturkNativePrivateClient::DebugString() const {
  double delta_t = (GetCurrentTimestamp() - start_time_) / 1.0e9;
  std::stringstream ss;
  ss << "BtcturkNativePrivateClient::DebugString\n";
  ss << "api info\n";
  for (auto& [name, value] : api_req_info_) {
    int32_t blocked = 0;
    if (api_block_info_.count(name) > 0) {
      blocked = api_block_info_.at(name);
    }
    int32_t total_req = value + blocked;
    ss << name << " (total:" << total_req << ", succeeded: " << value << ", blocked: " << blocked
       << ", req_rate: " << value / delta_t << ", block_rate: " << blocked / delta_t << ")\n";
  }
  return ss.str();
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::PlaceOrder(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  CHECK_API_LIMIT(ActionType::PLACE, QueryType::UNKNOWN);

  UrlParamsBuilder builder;
  builder.PutPost("pairSymbol", params.pair_symbol());
  builder.PutPost("newOrderClientId", params.client_order_id());
  builder.PutPost("orderType", params.order_type());
  builder.PutPost("quantity", params.quantity());
  builder.PutPost("price", params.price());
  builder.PutPost("orderMethod", params.order_method());
  auto* context = GetAuth()->CreateRequestByPostWithSignature("/api/v1/order", &builder);
  local_rate_tracker_->Push(1, ts, ActionType::PLACE, QueryType::UNKNOWN);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::CancelOrder(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  CHECK_API_LIMIT(ActionType::CANCEL, QueryType::UNKNOWN);

  UrlParamsBuilder builder;
  if (params.has_order_id()) {
    builder.PutGet("id", params.order_id());
  } else if (params.has_client_order_id()) {
    builder.PutGet("id", params.client_order_id());
  }
  auto* context = GetAuth()->CreateRequestByDeleteWithSignature("/api/v1/order", &builder);
  local_rate_tracker_->Push(1, ts, ActionType::CANCEL, QueryType::UNKNOWN);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::PlaceOrderNorm(
    const OrderExecution& order_exe) {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::CancelOrderNorm(
    const OrderExecution& order_exe) {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::SubmitOrderExecution(
    const OrderExecutionProto& order) {
  switch (order.type()) {
    case OrderExecutionProto::SUBMIT_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return PlaceOrder(params);
    }
    case OrderExecutionProto::CANCEL_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return CancelOrder(params);
    }
    default: {
      return nullptr;
    }
  }
}

std::shared_ptr<AsioHttpContext> BtcturkNativePrivateClient::SubmitRestQuery(
    const RestQueryProto& query) {
  RestParams params;
  switch (query.type()) {
    case RestQueryProto::QUERY_ACCOUNT_BALANCE: {
      return QueryAccountBalance();
    }
    case RestQueryProto::QUERY_OPEN_ORDERS: {
      params.set_pair_symbol("ETHUSDT");
      return QueryOpenOrders(params);
    }
    default: {
      return nullptr;
    }
  }
}
